package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.entity.*;
import com.ruan.mapper.*;
import com.ruan.query.OrdersQuery;
import com.ruan.service.OrdersService;
import com.ruan.utils.RedisCache;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
* @author 59499
* @description 针对表【orders】的数据库操作Service实现
* @createDate 2023-09-14 12:59:21
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Override
    public R<String> addOrder(String skuOptions, String userId, Integer addressId, Integer spuId, int num) {
        if (addressId == null){
            return new R<>(100,"请选择收货地址");
        }
        List<Sku> skuList = redisCache.getCacheList("getSkuBySpuId"+spuId);
        if (skuList.isEmpty()){
            QueryWrapper<Sku> wrapper = new QueryWrapper<>();
            wrapper.eq("spu_id",spuId);
            wrapper.eq("status",1);
            skuList = skuMapper.selectList(wrapper);
        }
        List<String> skuOptionsList = Arrays.asList(skuOptions.split(";"));
        Sku sku = new Sku();
        int i = 0;
        for (Sku s:skuList){
            List<String> skuListOptions = Arrays.asList(s.getProperties().split(";"));
            if(new HashSet<>(skuOptionsList).containsAll(skuListOptions) && new HashSet<>(skuListOptions).containsAll(skuOptionsList)){
                sku = s;
                i=1;
                break;
            }
        }
        if (i==0){
            return new R<>(100,"该规格商品已售空");
        }
        Integer stock = redisCache.getCacheObject("skuStock"+sku.getId());
        if (stock == null){
            redisCache.setCacheObject("skuStock"+sku.getId(),sku.getStock());
            stock=sku.getStock();
        }
        if (stock < num) {
            return new R<>(100,"该规格商品库存不足");
        }else{
            //不可在这里下单减库存，否则导致数据不安全
        }
        //减少库存
        Long value = redisCache.increment("skuStock"+sku.getId(), -num);
        //库存充足
        if (value >= 0) {
            sku.setStock(Math.toIntExact(value));
            skuMapper.updateById(sku);
            Orders orders = new Orders();
            orders.setUserId(userId);
            orders.setOrderNumber(UUID.randomUUID().toString());
            orders.setSkuId(sku.getId());
            orders.setSkuName(sku.getName());
            orders.setSkuPicture(sku.getPicture());
            orders.setPrice(sku.getPrice().multiply(BigDecimal.valueOf(num)));
            orders.setSpuId(sku.getSpuId());
            Spu spu = spuMapper.selectById(sku.getSpuId());
            orders.setCategoryId(spu.getCategoryId());
            Address address = addressMapper.selectById(addressId);
            orders.setConsignee(address.getConsignee());
            orders.setCity(address.getCity());
            orders.setDistrict(address.getDistrict());
            orders.setProvince(address.getProvince());
            orders.setDetailAddress(address.getDetailAddress());
            orders.setPhoneNumber(address.getPhoneNumber());
            orders.setNum(num);
            int row = ordersMapper.insert(orders);
            if (row != 1){
                redisCache.increment("skuStock"+sku.getId(), num);
                return new R<>(100,"订单生成失败");
            }
            rabbitTemplate.convertAndSend("orders-delayed-exchange","orders-delayed-routing-key",orders.getOrderNumber(),message -> {
                message.getMessageProperties().setDelay(7*24*60*60*1000);
                return message;
            });
            return new R<>(200,"下订单成功，请确认订单并支付",orders.getId());
        } else {
            //库存不足，需要增加刚刚减去的库存
            redisCache.increment("skuStock"+sku.getId(), num);
            return new R<>(100,"该规格商品库存不足");
        }
    }

    @Override
    public R<Orders> getOrderById(String id) {
        Orders orders = ordersMapper.selectById(id);
        return new R<>(200,"查询成功",orders);
    }

    @Override
    public Orders getOrderByOutTradeNo(String outTradeNo) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("order_number",outTradeNo);
        wrapper.eq("status",1);
        return ordersMapper.selectOne(wrapper);
    }

    @Override
    public R<List<Orders>> getOrdersListByUserId(String userId) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("status",1);
        List<Orders> ordersList = ordersMapper.selectList(wrapper);
        return new R<>(200,"查询成功",ordersList);
    }

    @Override
    public R<Void> deleteOrdersById(String id) {
        Orders orders = ordersMapper.selectById(id);
        orders.setStatus(0);
        int row = ordersMapper.updateById(orders);
        if (row != 1){
            return new R<>(100,"删除失败");
        }
        return new R<>(200,"删除成功");
    }

    @Override
    public R<IPage<Orders>> getAllOrders(OrdersQuery ordersQuery) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        if (ordersQuery.getUserId() != null && !Objects.equals(ordersQuery.getUserId(),"")){
            wrapper.eq("user_id",ordersQuery.getUserId());
        }
        if (ordersQuery.getOrderNumber() != null&& !Objects.equals(ordersQuery.getOrderNumber(), "")){
            wrapper.eq("order_number",ordersQuery.getOrderNumber());
        }
        if (ordersQuery.getSpuId() != null ){
            wrapper.eq("spu_id",ordersQuery.getSpuId());
        }
        if (ordersQuery.getCategoryId() != null ){
            wrapper.eq("category_id",ordersQuery.getCategoryId());
        }
        Page<Orders> ordersPage = new Page<>(ordersQuery.getPageNum(),ordersQuery.getPageSize());
        IPage<Orders> ordersIPage = ordersMapper.selectPage(ordersPage,wrapper);
        return new R<>(200,"查询成功",ordersIPage);
    }


}




